#include "GenericTypeDefs.h"
#include "buffer.h"

#define MODIFIED_IN     0
#define MODIFIED_OUT    1

void buildBuffer(buffer *buf, BYTE *bufArray, int bufSize){
    buf->outputBuffer = bufArray;
    buf->bufferSize = bufSize;
    buf->bufferStart = 0;
    buf->bufferEnd = 0;
    buf->lastModified = MODIFIED_OUT;
}

void bufferize(buffer *buf, const char *string){
    while(!fullBuffer(buf) && *string != '\0'){
        bufferizeChar(buf, *string);
        string++;
    }
}

BYTE fullBuffer(buffer *buf){
    return (buf->lastModified == MODIFIED_IN && buf->bufferEnd == buf->bufferStart);
}

BYTE emptyBuffer(buffer *buf){
    return (buf->lastModified == MODIFIED_OUT && buf->bufferEnd == buf->bufferStart);
}

BYTE nextBufferChar(buffer *buf){
    if(emptyBuffer(buf)) return 0xFF;
    char tmp = buf->outputBuffer[buf->bufferStart];
    buf->bufferStart++;
    buf->bufferStart %= buf->bufferSize;
    buf->lastModified = MODIFIED_OUT;
    return tmp;
}

void bufferizeChar(buffer *buf, char c){
    if(fullBuffer(buf)) return;
    buf->lastModified = MODIFIED_IN;
    buf->outputBuffer[buf->bufferEnd] = c;
    buf->bufferEnd++;
    buf->bufferEnd %= buf->bufferSize;
}

void resetBuffer(buffer *buf){
    buf->bufferStart = 0;
    buf->bufferEnd = 0;
    buf->lastModified = MODIFIED_OUT;
}